﻿using Common.EdgeBytes;
using Maticsoft.Common;
using MQXT.BLL;
using MQXT.Repository.DAL;
using MQXT.Repository.Model;
using Oliving.CommonPC.Log;
using ScokTcpLib;
using ScokTcpLib.ScokTcpServer;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SocketTool.Socket
{
    public static class TcpipCjq
    {

        #region 参数


        private static FzidPraser _praser;
        public static int _port = 5000;


        #endregion


        #region MyRegion



        public static void InitSocket()
        {
            try
            {
                EdgeLog.writeLog("button1_Click", "InitSocket ");

                // 50001 TCPIP_PortName
                _port = Convert.ToInt32(ConfigurationManager.AppSettings["TCPIP_PortName"]);

            }
            catch (Exception ex)
            {
                //记录服务器错误信息 
                EdgeLog.writeLog("Log_Service", (ex).ToString());
                return;
            }
            _praser = new FzidPraser();

            //创建服务器
            SocketComm.InitSocketServer(_port);

            SocketComm.getSockSvr().ClientConn += OnClientConn;
            SocketComm.getSockSvr().ClientClose += OnClientClose;

            SocketComm.getSockSvr().RecvData += OnRecvData;

            CheckDiaoXian();
        }


        #region 处理事件

        /// <summary>
        ///  客户端连接事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void OnClientConn(object sender, NetEventArgs e)
        {
            try
            {
                EdgeLog.writeLog("wpServoce", "Tcpip链接");
                EdgeLog.writeLog("wpServoce", "数量 "+ SocketComm.getSockSvr().SessionCount);

                //BeginInvoke(new ShowClientCountDele(ShowClientCount), new object[] { SocketComm.getSockSvr().SessionCount });
            }
            catch (System.Exception ex)
            {

            }
        }

        //private delegate void ShowClientCountDele(int count);
        //private static void ShowClientCount(int count)
        //{
        //    //lab_info.Text = string.Format(" {0}", count);

        //    //EdgeLog.writeLog("ShowClientCount", count);

        //}



        /// <summary>
        ///  客户端关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void OnClientClose(object sender, NetEventArgs e)
        {

            try
            {
                EdgeLog.writeLog("wpServoce", "Tcpip断开链接");
                //BeginInvoke(new ShowClientCountDele(ShowClientCount), new object[] { SocketComm.getSockSvr().SessionCount });

                // 根据sessionId 

                //string mySession = e.Client.IP + "_" + e.Client.ID.ID.ToString();


            }
            catch (System.Exception ex)
            {

            }
        }

        /// <summary>
        ///  接受数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void OnRecvData(object sender, NetEventArgs e)
        {

            string stringdata = BitConverter.ToString(e.Client.Datagram, 0, e.Client.DatagramLen);
            string strMsg = Encoding.UTF8.GetString(e.Client.Datagram, 0, e.Client.DatagramLen);


            //EdgeLog.writeLog("OnRecvData", stringdata); // 16进制数据
            //EdgeLog.writeLog("OnRecvDataA", strMsg);    // 字符串 
            // string mySession = e.Client.IP + "_" + e.Client.ID.ID.ToString();

            EdgeDataAnalysis.Check_ZhuCe(strMsg, e.Client.ID.ID.ToString());
             
            // EdgeLog.writeLog("Cjq_OnRecvData", stringdata); // 16进制数据
            // EdgeLog.writeLog("Cjq_OnRecvDataA", strMsg);    // 字符串
            // EdgeLog.writeLog("Cjq_Count", SocketComm.getSockSvr().SessionCount + "");    // 字符串


        }



        public static void EdgeSend(int addr, string content)
        {
            EdgeLog.writeLog("透传设置", " =>addr " + addr);    // 字符串
            List<string> sessionList = EdgeDataAnalysis.GetListSession(addr.ToString());

            foreach (DictionaryEntry dto in SocketComm.getSockSvr().SessionTable)
            {
                string sesssionID = ((Session)dto.Value).ID.ID.ToString();

                if (sessionList.Contains(((Session)dto.Value).ID.ID.ToString()))
                {
                    EdgeLog.writeLog("透传设置", " =>开始 ");    // 字符串
                    byte[] bytTemp2 = BytesHelper.EdgeGetBytes(content);
                    bool a = SocketComm.getSockSvr().Send((Session)dto.Value, bytTemp2, bytTemp2.Length, 0);
                    EdgeLog.writeLog("透传设置", content + " => " + a);    // 字符串
                }
            }


        }





        #endregion

        #endregion

        public static void CheckDiaoXian()
        {
            CaiJiQiModelService bll = new CaiJiQiModelService();
            Thread thread = new Thread(() =>
            {
                while (true)
                {
                    try
                    {

                        // List<CaiJiQiModel> cjqList = bll.Query(F => F.UpdateTIme < DateTime.Now.AddMinutes(-10));
                        List<CaiJiQiModel> cjqList = bll.Query(F => F.UpdateTIme < DateTime.Now.AddMinutes(-60 * 12));

                        if (cjqList != null && cjqList.Count > 0)
                        {
                            foreach (var cjq in cjqList)
                            {
                                bll.DiaoXian(cjq.CJQ_Id);
                            }
                        }

                    }
                    catch (Exception ee)
                    {
                        EdgeLog.writeLog("掉线异常", ee.ToString());
                    }
                    Thread.Sleep(2 * 60 * 1000);
                }
            });
            thread.IsBackground = true;
            thread.Start();
        }

    }


}
